"""VisitorSheet API endpoints."""

from __future__ import annotations

from datetime import date
from typing import Any, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from ...deps import get_visitor_sheet_service, get_ai_extraction_service, get_current_user, get_db
from ....schemas.visitor_sheet import (
    VisitorSheetCreate,
    VisitorSheetUpdate,
    VisitorSheetOut,
    VisitorSheetWithDetails,
    VisitorSheetListOut,
    VisitorSheetQuickCreate,
)
from ....services.visitor_sheet_service import VisitorSheetService
from ....services.ai_extraction_service import AIExtractionService
from ....repositories.follow_up_reminder_repository import FollowUpReminderRepository
from ....models.user import User

router = APIRouter(prefix="/visitor-sheets", tags=["visitor-sheets"])


@router.post(
    "/", response_model=VisitorSheetOut, status_code=status.HTTP_201_CREATED, summary="创建访客单"
)
def create_visitor_sheet(
    visitor_sheet_data: VisitorSheetCreate,
    service: VisitorSheetService = Depends(get_visitor_sheet_service),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> VisitorSheetOut:
    """
    创建新访客单（带看记录）。

    - **lead_id**: 客户ID（必填）
    - **property_id**: 房源ID（必填）
    - **agent_id**: 经纪人ID（必填）
    - **visit_date**: 带看日期（必填）
    - **satisfaction**: 满意度（1-5星，可选）
    - **intention**: 意向度（可选，默认medium）

    自动功能：
    - 创建成功后自动生成3天后的跟进提醒
    """
    try:
        visitor_sheet = service.create_visitor_sheet(visitor_sheet_data)

        # 自动创建跟进提醒（看房3天后）
        reminder_repo = FollowUpReminderRepository(db)
        reminder_repo.auto_create_visitor_sheet_reminder(
            visitor_sheet_id=visitor_sheet.id,
            lead_id=visitor_sheet.lead_id,
            assigned_to=visitor_sheet.agent_id,  # 分配给经纪人
            days_after=3,  # 3天后提醒
        )
        db.commit()

        return visitor_sheet
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e


@router.get("/", response_model=VisitorSheetListOut, summary="获取访客单列表")
def get_visitor_sheets(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    lead_id: Optional[int] = Query(None, description="客户ID"),
    property_id: Optional[int] = Query(None, description="房源ID"),
    agent_id: Optional[int] = Query(None, description="经纪人ID"),
    start_date: Optional[date] = Query(None, description="开始日期"),
    end_date: Optional[date] = Query(None, description="结束日期"),
    intention: Optional[str] = Query(None, description="意向度"),
    service: VisitorSheetService = Depends(get_visitor_sheet_service),
) -> VisitorSheetListOut:
    """
    获取访客单列表（分页）。

    支持筛选条件：
    - 客户ID
    - 房源ID
    - 经纪人ID
    - 日期范围
    - 意向度
    """
    skip = (page - 1) * page_size

    try:
        items, total = service.get_visitor_sheets(
            skip=skip,
            limit=page_size,
            lead_id=lead_id,
            property_id=property_id,
            agent_id=agent_id,
            start_date=start_date,
            end_date=end_date,
            intention=intention,
        )

        return VisitorSheetListOut(total=total, items=items, page=page, page_size=page_size)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e


@router.get("/{visitor_sheet_id}", response_model=VisitorSheetWithDetails, summary="获取访客单详情")
def get_visitor_sheet(
    visitor_sheet_id: int, service: VisitorSheetService = Depends(get_visitor_sheet_service)
) -> VisitorSheetWithDetails:
    """获取指定访客单的详细信息（包含关联客户、房源、经纪人信息）。"""
    visitor_sheet = service.get_visitor_sheet(visitor_sheet_id, with_details=True)
    if not visitor_sheet:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail=f"访客单 ID {visitor_sheet_id} 不存在"
        )

    # Type assertion: with_details=True guarantees VisitorSheetWithDetails
    assert isinstance(visitor_sheet, VisitorSheetWithDetails)
    return visitor_sheet


@router.put("/{visitor_sheet_id}", response_model=VisitorSheetOut, summary="更新访客单")
def update_visitor_sheet(
    visitor_sheet_id: int,
    visitor_sheet_data: VisitorSheetUpdate,
    service: VisitorSheetService = Depends(get_visitor_sheet_service),
) -> VisitorSheetOut:
    """更新访客单信息（如满意度、意向度等）。"""
    updated_visitor_sheet = service.update_visitor_sheet(visitor_sheet_id, visitor_sheet_data)
    if not updated_visitor_sheet:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail=f"访客单 ID {visitor_sheet_id} 不存在"
        )

    return updated_visitor_sheet


@router.delete(
    "/{visitor_sheet_id}",
    status_code=status.HTTP_204_NO_CONTENT,
    summary="删除访客单",
    response_model=None,
)
def delete_visitor_sheet(
    visitor_sheet_id: int, service: VisitorSheetService = Depends(get_visitor_sheet_service)
) -> None:
    """删除指定访客单。"""
    deleted = service.delete_visitor_sheet(visitor_sheet_id)
    if not deleted:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail=f"访客单 ID {visitor_sheet_id} 不存在"
        )


@router.get("/stats/satisfaction", summary="获取满意度统计")
def get_satisfaction_stats(
    property_id: Optional[int] = Query(None, description="房源ID"),
    agent_id: Optional[int] = Query(None, description="经纪人ID"),
    service: VisitorSheetService = Depends(get_visitor_sheet_service),
) -> dict[str, Any]:
    """
    获取满意度统计数据。

    可按房源或经纪人筛选。
    """
    try:
        stats = service.get_satisfaction_stats(property_id=property_id, agent_id=agent_id)
        return stats
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) from e


@router.post("/extract-info", summary="从备注提取访客单信息（Phase 2: AI辅助）")
def extract_visitor_sheet_info(
    notes: str = Query(..., min_length=10, max_length=2000, description="带看情况备注"),
    community_name: Optional[str] = Query(None, description="小区名称（可选，用于房源匹配）"),
    ai_service: AIExtractionService = Depends(get_ai_extraction_service),
) -> dict[str, Any]:
    """
    从带看情况备注中提取访客单信息（Phase 2: 快捷模式）

    使用混合架构（规则引擎 + AI语义分析）自动提取：
    - satisfaction: 满意度（1-5星）
    - intention: 意向度（high/medium/low）
    - pros_tags: 优点标签
    - cons_tags: 缺点标签
    - visit_time: 带看时间
    - duration_minutes: 停留时长

    返回示例：
    {
        "satisfaction": 4,
        "intention": "high",
        "pros_tags": "采光好,户型方正",
        "cons_tags": "租金偏贵",
        "visit_time": "14:00",
        "duration_minutes": 45,
        "confidence": 0.85,
        "extraction_method": "hybrid"
    }
    """
    try:
        result = ai_service.extract_visitor_sheet_info(notes, community_name)
        return result
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"提取失败: {str(e)}"
        ) from e


@router.post(
    "/quick-create",
    response_model=VisitorSheetOut,
    status_code=status.HTTP_201_CREATED,
    summary="快捷创建访客单（Phase 2: 快捷模式）"
)
def quick_create_visitor_sheet(
    data: VisitorSheetQuickCreate,
    service: VisitorSheetService = Depends(get_visitor_sheet_service),
    ai_service: AIExtractionService = Depends(get_ai_extraction_service),
) -> VisitorSheetOut:
    """
    快捷创建访客单（Phase 2: 访客单快捷模式）

    核心流程：
    1. 用户输入3个必填字段：客户、房源、带看情况
    2. AI自动从"带看情况"中提取满意度、意向度、优缺点等
    3. 用户可在前端编辑AI提取结果后提交
    4. 一键创建完整访客单

    必填字段（3个）：
    - lead_id: 客户ID
    - property_id: 房源ID
    - agent_id: 经纪人ID
    - visit_date: 带看日期
    - quick_notes: 带看情况（AI将从此提取其他字段）

    可选字段（AI自动填充，用户可编辑）：
    - satisfaction: 满意度
    - intention: 意向度
    - pros_tags: 优点标签
    - cons_tags: 缺点标签
    - visit_time: 带看时间
    - duration_minutes: 停留时长
    """
    try:
        # 1. 如果前端未提供AI提取字段，后端自动提取
        extracted_data = {}
        if not data.satisfaction or not data.intention:
            extracted = ai_service.extract_visitor_sheet_info(data.quick_notes, community_name=None)
            extracted_data = extracted

        # 2. 合并数据（前端提供的字段优先）
        from datetime import time as datetime_time

        # 转换 intention 字符串为枚举
        intention_value = data.intention
        if not intention_value and "intention" in extracted_data:
            intention_str = extracted_data["intention"]
            from ....models.enums import IntentionLevel
            if intention_str == "high":
                intention_value = IntentionLevel.HIGH
            elif intention_str == "low":
                intention_value = IntentionLevel.LOW
            else:
                intention_value = IntentionLevel.MEDIUM

        # 转换 visit_time 字符串为 time 对象
        visit_time_value = data.visit_time
        if not visit_time_value and "visit_time" in extracted_data:
            time_str = extracted_data["visit_time"]
            try:
                hour, minute = map(int, time_str.split(":"))
                visit_time_value = datetime_time(hour, minute)
            except Exception:
                pass

        # 3. 创建完整的访客单数据
        visitor_sheet_create = VisitorSheetCreate(
            lead_id=data.lead_id,
            property_id=data.property_id,
            agent_id=data.agent_id,
            visit_date=data.visit_date,
            visit_time=visit_time_value or extracted_data.get("visit_time"),
            duration_minutes=data.duration_minutes or extracted_data.get("duration_minutes"),
            satisfaction=data.satisfaction or extracted_data.get("satisfaction"),
            intention=intention_value or IntentionLevel.MEDIUM,
            pros_tags=data.pros_tags or extracted_data.get("pros_tags"),
            cons_tags=data.cons_tags or extracted_data.get("cons_tags"),
            notes=data.quick_notes,
        )

        # 4. 创建访客单
        return service.create_visitor_sheet(visitor_sheet_create)

    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"创建失败: {str(e)}"
        ) from e
